import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.api.response.api.BaseChargeResp;
import com.binguo.api.response.api.BaseUserInfo;
import com.binguo.api.service.ApiOrderService;
import com.binguo.api.service.api.ShopApiInterface;
import com.binguo.common.enums.PayStatus;
import com.binguo.common.enums.PayType;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.Base64Util;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.model.Branch;
import com.binguo.model.model.CashierDesk
import com.binguo.model.model.PayCard;
import com.binguo.model.model.ShopXindaConfig;
import com.binguo.model.repository.BranchRepository;
import com.binguo.model.repository.CashierDeskRepository;
import com.binguo.model.repository.ShopXindaConfigRepository;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List

import static com.binguo.common.exception.ErrorCode.PAYCARD_NOT_SUFFICIENT_FUNDS;


/**
 * @author yuritian
 * @Title: XinDaPayService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020/5/1910:22
 */
public class XinDaService implements ShopApiInterface {

    private static Logger logger = LoggerFactory.getLogger(XinDaService.class);

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    @Resource
    ApiOrderService apiOrderService;

    @Resource
    ShopXindaConfigRepository shopXindaConfigRepository;

    @Resource
    CashierDeskRepository cashierDeskRepository;

    @Resource
    BranchRepository branchRepository;

    @Override
    public BaseChargeResp payPreHandler(OrderDTO orderDTO) {
        BaseChargeResp<OrderVO> result = new BaseChargeResp<>();
        if (orderDTO.getPayType().equals(PayType.CARDPAY)){
            OrderVO orderVO = apiOrderService._createOrder(orderDTO, PayStatus.SUCCESS);
            result.setData(orderVO);
            result.setCode(200);
            return result;
        }else if (orderDTO.getPayType().equals(PayType.MICROPAY)){
            return qrCodePay(orderDTO);
        }else {
            throw new ServiceException("不支持支付方式");
        }
    }

    @Override
    public BaseChargeResp payPostHandler(OrderDTO orderDTO) {

        return null;
    }

    @Override
    public BaseUserInfo getUserInfo(String cardNo) {
        return null;
    }

    @Override
    public BaseChargeResp getProductList() {
        return null;
    }

    @Override
    public BaseChargeResp cardPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp wxPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp aliPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp facePay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp cashPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp qrCodePay(OrderDTO orderDTO) {

        BaseChargeResp<OrderVO> resp = new BaseChargeResp<>();

        Condition condition = new Condition(ShopXindaConfig.class);
        condition.or().andEqualTo("shopId",orderDTO.getShopId());
        List<ShopXindaConfig> configList = shopXindaConfigRepository.findByCondition(condition);
        if (null == configList || configList.size() == 0){
            throw new ServiceException("商户信息配置有误");
        }
        String stationCode = configList.get(0).getStationcode();

        CashierDesk cashierDesk =  cashierDeskRepository.findById(orderDTO.getCashierDeskId());

        String poscode = cashierDesk.getShopWebId();

        Branch branch = branchRepository.findById(cashierDesk.getBranchid());

        String meraccno = branch.getWebBranchId();

        XinDaPayVO payVO = new XinDaPayVO();
        payVO.setTxamt(orderDTO.getRealFee().toString());
        payVO.setMeraccno(meraccno);
        payVO.setStationcode(stationCode);
        payVO.setTxdate(dateFormat.format(new Date()));
        payVO.setPoscode(poscode);
        payVO.setPosjourno(orderDTO.getOrderNo());
        JSONObject result = xinDaPay(payVO,orderDTO.getAuthCode());
        String returncode = result.getString("returncode");
        if (returncode.equals("SUCCESS")) {
            OrderVO orderVO = apiOrderService._createOrder(orderDTO, PayStatus.SUCCESS);
            PayCard pc = new PayCard();
            pc.setAccountbalance(100);
            orderVO.setPayCard(pc);

            resp.setData(orderVO);
            resp.setCode(200);
            return resp;
        }else {
            if (result.getString("returnmsg").equals("余额不足")){
                throw new ServiceException(PAYCARD_NOT_SUFFICIENT_FUNDS);
            }else {
                throw new ServiceException(result.getString("returnmsg"));
            }
        }
    }

    public JSONObject xinDaPay(XinDaPayVO payVO,
                               String codecontent){
        String jsonStr = JSONObject.toJSONString(payVO);
        JSONObject param = JSON.parseObject(jsonStr);
        param.put("codecontent",codecontent);
        logger.info("新大发送数据:"+ param.toJSONString());
        return doSelectRiskReportForm(param.toJSONString());
    }


    public JSONObject doSelectRiskReportForm(String param){
        //调用接口
        //方法一:直接AXIS调用远程的web service
        try {
            String endpoint = "http://111.115.76.14:8080/TransferService/services/ICardService";
            Service service = new Service();
            Call call = service.createCall();
            call.setTargetEndpointAddress(endpoint);
            // 参数名//对应的是 public String printWord(@WebParam(name = "settle_num") String settle_num);
            String parametersName = "in0";
            // 调用的方法名//当这种调用不到的时候,可以使用下面的,加入命名空间名
            call.setOperationName(QName.valueOf("receiveFromThird"));
            //参数名//XSD_STRING:String类型//.IN入参
            call.addParameter(parametersName, XMLType.XSD_STRING, ParameterMode.IN);
            // 返回值类型：String
            call.setReturnType(XMLType.XSD_STRING);
            param = Base64Util.encode(param.getBytes());
            // 远程调用
            Object[] postParamArray = new Object[1];
            postParamArray[0] = param;
            String result = (String) call.invoke(postParamArray);
            logger.info(new String(Base64Util.decode(result)));
            JSONObject resultObject = JSONObject.parseObject(new String(Base64Util.decode(result)));
            return resultObject;
        } catch (Exception e) {
            logger.error(e.toString());
            throw new ServiceException("支付失败,服务器异常");
        }
    }
}

class XinDaPayVO {
    private String txamt;
    private String meraccno;
    private String stationcode;
    private String txdate;
    private String poscode;
    private String posjourno;String getTxamt() {
        return txamt
    }

    void setTxamt(String txamt) {
        this.txamt = txamt
    }

    String getMeraccno() {
        return meraccno
    }

    void setMeraccno(String meraccno) {
        this.meraccno = meraccno
    }

    String getStationcode() {
        return stationcode
    }

    void setStationcode(String stationcode) {
        this.stationcode = stationcode
    }

    String getTxdate() {
        return txdate
    }

    void setTxdate(String txdate) {
        this.txdate = txdate
    }

    String getPoscode() {
        return poscode
    }

    void setPoscode(String poscode) {
        this.poscode = poscode
    }

    String getPosjourno() {
        return posjourno
    }

    void setPosjourno(String posjourno) {
        this.posjourno = posjourno
    }
}